<template>
  <div class="loginContant" ref="loginContant">
    <!-- <div class="logo"></div> -->
    <div class="loginForm">
      <h3>用户运营管理系统</h3>
      <h4>HI,感谢再次登录用户运营管理系统</h4>
      <a-form
        id="components-form-demo-normal-login"
        :form="form"
        class="login-form"
        @submit="handleSubmit"
      >
        <a-form-item>
          <a-input
            v-decorator="[
              'userName',
              { rules: [{ required: true, message: '用户名不正确!'}] }
            ]"
            placeholder="用户名"
          >
            <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-input
            v-decorator="[
              'password',
              { rules: [{ required: true, message: '密码不能低于6位!', min: 6 }] }
            ]"
            type="password"
            placeholder="密码"
          >
            <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-checkbox
            v-decorator="[
              'remember',
              {
                valuePropName: 'checked',
                initialValue: true
              }
            ]"
          >
            <a class="checkPassword">记住密码</a>
          </a-checkbox>
          <a class="login-form-forgot" @click="showModal">忘记密码？</a>
          <a-button type="primary" :loading="loading" @click="handleSubmit">登录</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script>
import { login } from "@/api/login";
import throttle from "lodash.throttle"; //节流
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      loading: false,
      visible: false,
      confirmLoadingLoading: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        }
      },
      tailFormItemLayout: {
        wrapperCol: {
          xs: {
            span: 24,
            offset: 0
          },
          sm: {
            span: 16,
            offset: 8
          }
        }
      },
      btnText: "获取验证码",
      myInterval: null
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "normal_login" });
    this.findform = this.$form.createForm(this, { name: "findpassword" });
  },
  mounted() {
    // 页面加载时获取cookie值
    this.getCookie();
    window.addEventListener("resize", this.observe);
    this.observe();
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.observe);
    });
  },
  methods: {
    observe: throttle(function() {
      const dom = this.$refs.loginContant;
      const width = Math.max(dom.scrollWidth, 1200);
      dom.style.height = `${(920 / 1920) * width}px`;
    }, 100),
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true;
          login({ loginName: values.userName, password: values.password })
            .then(res => {
              console.log(res);
              if (res.data.code === 200) {
                localStorage.setItem("TOKEN", res.data.data.token);
                localStorage.setItem(
                  "refreshToken",
                  res.data.data.refreshToken
                );
                localStorage.setItem("userInfo", JSON.stringify(res.data.data));
                if (values.remember) {
                  // 调用setCookie()方法保存cookie
                  this.setCookie(values.userName, values.password, 7);
                } else {
                  // 调用clearCookie()方法清空cookie
                  this.clearCookie();
                }
                if (res.data.data.type === 0) {
                  //普通用户路由跳转
                  this.$router.push("/common_user");
                  this.$message.destroy();
                  this.$message.success(res.data.msg);
                } else if (res.data.data.type === -1) {
                  //超级管理员路由跳转
                  this.$router.push("/console");
                  this.$message.destroy();
                  this.$message.success(res.data.msg);
                } else if (res.data.data.type === 1) {
                  this.$message.destroy();
                  this.$message.error("暂无权限登录");
                }
              } else {
                this.$message.destroy();
                this.$message.error(res.data.msg);
              }
            })
            .catch(err => {
              console.log(err);
              this.$message.destroy();
              this.$message.error(err);
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.findform;
      if (value && value !== form.getFieldValue("password")) {
        callback("两次输入的密码不一致!");
      } else {
        callback();
      }
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.findform;
      if (value && this.confirmDirty) {
        form.validateFields(["confirm"], { force: true });
      }
      callback();
    },
    compareToPhone(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error("请输入正确的手机号!"));
      } else {
        callback();
      }
    },
    showModal() {
      this.visible = true;
    },
    onClose() {
      this.visible = false;
    },
    // 设置cookie
    setCookie(userName, password, exdays) {
      var date = new Date();
      date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * exdays); // 这里是设置的是3天
      // 拼接cookie
      window.document.cookie =
        "userName" + "=" + userName + ";path=/;expires=" + date.toGMTString();
      window.document.cookie =
        "password" + "=" + password + ";path=/;expires=" + date.toGMTString();
    },
    // 读取cookie
    getCookie() {
      if (document.cookie.length > 0) {
        // 通过分号(;)作为分割符cookie字符串
        var arr = document.cookie.split(";");
        // 循环遍历分隔后字符串数组
        for (var i = 0; i < arr.length; i++) {
          // 再将字符串通过等号(=)进行分割
          var arr2 = arr[i].split("=");
          // 判断查找相对应的值,replace(/\s*/g, "")表示去掉字符串中的空格
         if (arr2[0].replace(/\s*/g, "") === "userName") {
            this.form.setFieldsValue({ userName: arr2[1] });
          } else if (arr2[0].replace(/\s*/g, "") === "password") {
            this.form.setFieldsValue({ password: arr2[1] });
          }
        }
      }
    },
    // 清除cookie
    clearCookie: function() {
      this.setCookie("", "", -1); // 将值置为空，天数为负即可
    },
    ...mapMutations({
      setUserInfo: "SET_USERINFO"
    })
  },
  destroyed() {
    if (this.myInterval) {
      clearInterval(this.myInterval);
    }
  }
};
</script>
<style lang="stylus" rel="stylesheet/stylus">
@import '~stylus/mixin.styl'
.loginContant
  background: url('../../assets/images/bg.png')
  height: 100%
  width: 100%
  background-size: 100% 100%
  overflow: hidden
  min-width: 1200px
  .logo
    width: 270px
    height: 76px
    background: url('../../assets/images/logos.png')
    background-size: 100% 100%
    margin-top: 50px
    margin-left: 50px
  .loginForm
    width: 400px
    height: 500px
    position: absolute
    top: 18%
    right: 16%
    h3
      height: 38px
      line-height: 38px
      font-size: 28px
      font-weight: 700
      margin-bottom: 0
      color: #fff
    h4
      height: 20px
      line-height: 20px
      font-size: 16px
      color: #777
      margin-top: 10px
      margin-bottom: 60px
    .ant-input
      height: 50px !important
    .ant-btn
      height: 50px
      border: none
      margin-top: 20px
      width: 100%
    .login-form-forgot
      float: right
      color: #ffffff
    .checkPassword
      color: #ffffff
.ant-drawer-content
  .ant-input
    height: 40px !important
  .ant-btn
    height: 40px
</style>

<style></style>
